package gui;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.io.OutputStream;
import java.io.PrintStream;

public class CC_Stream extends PrintStream {
    private JTextArea mainComponent;
    private int type;
    private int lineLimit;
    public static int OUT = 0;
    public static int ERR = 1;
    public static int NOTICE = 2;
    public static int PACKET = 3;

    public CC_Stream(OutputStream out, JTextArea mainComponent) {
        super(out);
        this.mainComponent = mainComponent;
        this.type = 3;
        this.lineLimit = 100;
    }

    public CC_Stream(OutputStream out, JTextArea mainComponent, int type) {
        super(out);
        this.mainComponent = mainComponent;
        this.type = type;
        this.lineLimit = 100;
    }

    public CC_Stream(OutputStream out, JTextArea mainComponent, int type, int lineLimit) {
        super(out);
        this.mainComponent = mainComponent;
        this.type = type;
        this.lineLimit = lineLimit;
    }

    @Override
    public void write(byte[] buf, int off, int len) {
        super.write(buf, off, len);
        String message = new String(buf, off, len);
        Color col;
        switch (this.type) {
            case 0 -> {
                col = Color.BLACK;
            }
            case 1 -> {
                col = Color.RED;
            }
            case 2 -> {
                col = Color.BLUE;
            }
            case 3 -> {
                col = Color.GRAY;
            }
            default -> {
                col = Color.BLACK;
            }
        }
        SwingUtilities.invokeLater(() -> {
            SimpleAttributeSet attrSet = new SimpleAttributeSet();
            StyleConstants.setForeground(attrSet, col);
            Document docMain = CC_Stream.this.mainComponent.getDocument();
            try {
                String[] docMainInfo = docMain.getText(0, docMain.getLength()).split("\r\n");
                if (docMainInfo.length >= CC_Stream.this.lineLimit + 1) {
                    for (int i = 0; i <= docMainInfo.length - CC_Stream.this.lineLimit - 1; ++i) {
                        docMain.remove(0, docMainInfo[i].length() + 2);
                    }
                }
                docMain.insertString(docMain.getLength(), message, attrSet);
            } catch (BadLocationException e) {
                CC_Stream.this.mainComponent.setText("输出出错:" + e + "\r\n內容:" + message + "\r\n类型:" + CC_Stream.this.type);
            }
        });
    }

    public static void cleanMessage(JTextArea mainComponent) {
        mainComponent.setText("");
    }
}
